package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
)

var HomePage = new(homepageService)

type homepageService struct{}

func (s *homepageService) List(c *gin.Context, req *model.ReqList) (*[]tables.HomeMenu, int64, error) {
	account, err := Request.Account(c)
	if err != nil {
		return nil, 0, err
	}
	where := fmt.Sprintf("acid=%d", account.Id)
	var m []tables.HomeMenu
	count, err := tableCommon.QueryListWithPageV2(where, req.PageNo, req.PageSize).OrderBy("id desc").
		FindAndCount(&m)
	if err != nil {
		return nil, 0, err
	}
	return &m, count, nil
}
func (s *homepageService) Save(c *gin.Context, req *tables.HomeMenu) error {
	account, err := Request.Account(c)
	if err != nil {
		return err
	}
	if req.Id == 0 {
		req.Acid = account.Id
		_, err = orm.Db.Insert(req)
		if err != nil {
			return err
		}
	} else {
		_, err = orm.Db.ID(req.Id).Update(req)
		if err != nil {
			return err
		}
	}
	return nil
}
func (s *homepageService) Info(c *gin.Context, where string, field string) (*tables.HomeMenu, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	var m tables.HomeMenu
	get, err := orm.Db.Where(where).Where("acid=?", user.Acid).Cols(field).Get(&m)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取数据不存在")
	}
	return &m, nil
}
func (s *homepageService) Infos(c *gin.Context, where string, field string) (*[]tables.HomeMenu, error) {
	user, err := Request.User(c)
	if err != nil {
		return nil, err
	}
	var m []tables.HomeMenu
	err = orm.Db.Where(where).Where("acid=?", user.Acid).Cols(field).Find(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func (s *homepageService) Del(c *gin.Context, req *model.ReqId) error {
	account, err := Request.Account(c)
	if err != nil {
		return err
	}
	d, err := orm.Db.ID(req.Id).Where("acid=?", account.Id).Delete(&tables.HomeMenu{})
	if err != nil {
		return err
	}
	if d == 0 {
		return errors.New("删除失败")
	}
	return nil
}
func (s *homepageService) WxMenu(c *gin.Context) ([]*model.HomeMenu, error) {
	accountR, _ := Request.Account(c)
	var nodes []*model.HomeMenu
	err := orm.Db.Where("acid = ?", accountR.Id).Find(&nodes)
	if err != nil {
		return nil, err
	}
	nodeMap := make(map[int]*model.HomeMenu)
	var roots []*model.HomeMenu
	// 先将所有节点存入 map
	for _, node := range nodes {
		nodeMap[node.Id] = node
	}
	// 构建树结构
	for _, node := range nodes {
		if node.ParentId == 0 {
			roots = append(roots, node)
		} else {
			parent, exists := nodeMap[node.ParentId]
			if exists {
				parent.Children = append(parent.Children, node)
			}
		}
	}
	return roots, nil
}
